<!--合约详情-->
<template>
  <div class="bg" @viewappear="viewappear" @viewdisappear="viewdisappear" @rightBtn="rightBtn">

    <scroller class="scroller bg1" :show-scrollbar="false">
      <div class="wrapper" v-if="isShow">
        
        <!--跟单-基础信息-->
        <div class="info" v-if="detailData.isFollow">
          <div class="row acenter">
            <div class="row aend">
              <text class="font32 text1">{{T(detailData.strategyName)}}</text>
              <text class="font24 text3" v-if="detailData.strategyCode">{{'  '+detailData.strategyCode}}</text>
            </div>
            <div class="all"></div>
            <text class="font28 text1">{{T('跟单佣金')+':'+detailData.commission+'VTN/日'}}</text>
          </div>

          <div class="height20"></div>
          <text class="font24 text3">{{parseTime1(detailData.startTime)+'-('+getExecuteTime(detailData.startTime)+')'}}</text>
          
          <div class="line1 bg3"></div>

          <div class="row acenter" @click="userClick(detailData.followUserId)">
          <LImage class="image" :src="detailData.avatar"></LImage>  
          <text class="font32 text1">{{detailData.nickName}}</text>
          <div class="all"></div>
          <LImage class="arrow" :src="Config.img('strategy_arrow.png')"></LImage>
          </div>
        </div>
        
        <!--其他-基础信息-->
        <div class="info" v-else>

          <div class="row acenter">
            <div class="row aend">
              <text class="font32 text1">{{T(detailData.strategyName)}}</text>
              <text class="font24 text3" v-if="detailData.strategyCode">{{'  '+detailData.strategyCode}}</text>
            </div>
            <div class="all"></div>
            
            <div class="row acenter"  v-if="detailData.states=='EXECUTE' 
                                          && configMap.signal 
                                          && configMap.signal.openSignal 
                                          && detailData.signalStates==0">
              <LImage class='msg' :src="Config.img('dengdai.png')"></LImage>
              <text class="font24 udRed-t1">{{T('等待信号触发')}}</text>
            </div>
            <text v-else :class="['font28', (detailData.states == 'EXECUTE' ?  'main-t1' : 'text3')]">{{getStateStr(detailData)}}</text>
          </div>

          <div class="height20"></div>
          <div class="row aend">
            <text class="font24 text3">{{parseTime1(detailData.startTime)+'-('+getExecuteTime(detailData.startTime)+')'}}</text>
            <div class="all"></div>
            <text class="font28 text3" v-if="detailData.isOpenFollow==true">{{T("开放跟单")}}</text>
          </div>
        </div>

        <div class="height20"></div>
        <div class="tips-bg row acenter" v-if="math.getNumber(account.riskRate) !=0 && math.getNumber(account.riskRate) < 150" @click="addContractClick">
          <text class="font24 tips-text all">{{T("策略担保资产率已降到${1}%请注意强平风险").replace("${1}", account.riskRate)}}</text>
          <LImage class="img-right" :src="Config.img('my_jiantou_huise.png')"></LImage>
        </div>

        <div class="height20"></div>
        <div class="row plpr40">
          <text class="font28 text2">{{getExchangeName()}}</text>
          

          <div :class="['short-long', Config.upDownBg(contract_num, 'short-long-red', 'short-long-green')]">
            <text :class="['font20',Config.upDownFont(contract_num)]">{{ getMoreOrShort()}}</text>
          </div>
        </div>

        <div class="height20"></div>
        <div class="row plpr40">
          <text class="font24 text3">{{ T("总投入")+"("+tradePairs.investCoin+")" }}</text>
          <div class="all"></div>
          <text class="font24 text3">{{ T("总收益")+"("+tradePairs.investCoin+")" }}</text>
        </div>

        <div class="height12"></div>
        <div class="row plpr40">
          <text class="font32 text2">{{ tradePairs.investCoinnNum }}</text>
          <div class="all"></div>
          <text :class="['font32', Config.upDownFont(detailData.realEarnings)]">{{getValueDelete(tradePairs.investCoin,detailData.realEarnings)+'('+detailData.realEarningsRate+'%)'}}</text>
        </div>

        <!--策略运行信息-->
        <div class="height40"></div>
        <div class="line bg3"></div>
        <div class="height40"></div>
        <div class="cell-run">

          <div class="cell-run-left all">
            <text class="font24 text3">{{T('账户权益')+'('+tradePairs.investCoin+')'}}</text>
            <div class="height12"></div>
            <text class="font24 text2">{{getValueDelete(tradePairs.investCoin, account.marginBalance)}}</text>
          </div>

          <div class="cell-run-left all">
            <text class="font24 text3">{{T('持仓盈亏')+'('+tradePairs.investCoin+')'}}</text>
            <div class="height12"></div>
            <text :class="['font24', Config.upDownFont(detailData.floatEarnings)]">{{getValueDelete(tradePairs.investCoin, detailData.floatEarnings)}}</text>
          </div>

          <div class="cell-run-right all">
            <text class="font24 text3">{{T('总年化')}}</text>
            <div class="height12"></div>
            <text :class="['font24', Config.upDownFont(detailData.realYearIncome)]">{{getAddStr(detailData.realYearIncome)+'%'}}</text>
          </div>
        </div>

        <div class="height40"></div>
        <div class="line bg3"></div>
        <div class="height40"></div>
        <div class="cell-run">

            <div class="cell-run-left all">
              <text class="font24 text3">{{T('当前价')+'(USDT)'}}</text>
              <div class="height12"></div>
              <text class="font24 text2">{{getValueDelete(tradePairs.investCoin, detailData.last)}}</text>
            </div>

            <div class="cell-run-left all">
              <div class="row acenter" @click="questionClick('强平价')">
                <text class="font24 text3">{{T('强平价')+'(USDT)  '}}</text>
                <LImage class="img-question" :src="Config.img('wenhao.png')"></LImage>
              </div>
              
              <div class="height12"></div>
              <text class="font24 text2">{{isShowZero(tradePairs.investCoin, account.liquidationPrice)}}</text>
              
            </div>

            <div class="cell-run-right all">
              <div class="row acenter" @click="questionClick('担保资产率')">
                <text class="font24 text3">{{T('担保资产率')+'  '}}</text>
                <LImage class="img-question" :src="Config.img('wenhao.png')"></LImage>
              </div>
              <div class="height12"></div>
              <text class="font24 text2">{{isShowZero("%", account.riskRate)}}</text>
            </div>
        </div>

        <div class="height28"></div>
        <div class="cell-run">

            <div class="cell-run-left all">
              <div class="row acenter" @click="questionClick('开仓阈值')">
                <text class="font24 text3">{{T('开仓阈值')+"  "}}</text>
                <LImage class="img-question" :src="Config.img('wenhao.png')"></LImage>
              </div>
              <div class="height12"></div>
              <text class="font24 text2">{{getmul100(tradePairs.openThreshold)+"%"}}</text>
            </div>

            <div class="cell-run-left all">
            </div>
            
            <div class="cell-run-right all">
            </div>
        </div>


        <!-- 套利记录 -->
        <div class="height40"></div>
        <div class="line bg3"></div>
        <div class="height40"></div>
        <text class="font30 text1 plpr40">{{T("套利记录")}}</text>
        <div class="height20"></div>
        <div class="cell-run">

            <div class="cell-run-left all">
              <text class="font24 text3">{{T('累计开仓')}}</text>
              <div class="height12"></div>
              <text class="font24 text2">{{detailData.finishOpenCount}}</text>
            </div>

            <div class="cell-run-left all">
              <text class="font24 text3">{{T('累计平仓')}}</text>
              <div class="height12"></div>
              <text class="font24 text2">{{detailData.finishCloseCount}}</text>
            </div>

            <div class="cell-run-right all">
              <text class="font24 text3">{{T('交易数')}}</text>
              <div class="height12"></div>
              <text class="font24 text2">{{detailData.finishBuySellCount}}</text>
            </div>
        </div>


        <!-- 收益分析 -->
        <div class="height40"></div>
        <div class="line bg3"></div>
        <div class="height40"></div>
        <div class="row acenter plpr40">
          <text class="font30 text1">{{T("收益分析")}}</text>
          <div class="all"></div>
          <div class="img-earning-rate main1"></div>
          <text class="font24 text2">{{T("总收益率")}}</text>
        </div>
        <div class="height20"></div>
        <WeexLineChart class="lineChart" :data="lineChartData"></WeexLineChart>

        <!-- 止盈止损 -->
        <div class="height40"></div>
        <text class="font30 text1 plpr40">{{T("止盈止损")}}</text>
        <div class="height28"></div> 
        <div class="cell-run">
          <div class="cell-run-left all">
            <text class="font24 text3">{{T('止盈率')}}</text>
            <div class="height12"></div>
            <text class="font24 text2">{{stopProfit}}</text>
          </div>

          <div class="cell-run-left all">
            <text class="font24 text3">{{T('止损率')}}</text>
            <div class="height12"></div>
            <text class="font24 text2">{{stopLoss}}</text>
          </div>

          <div class="cell-run-right all">
            <text class="font24 text3">{{T('自动终止时间')}}</text>
            <div class="height12"></div>
            <text class="font24 text2">{{stopTime}}</text>
          </div>
        </div>

        <!-- 持仓 -->
        <div class="height40"></div>
        <div class="line bg3"></div>
        <div class="height40"></div>
        <div class="column plpr40">
          <text class="font30  text1 ">{{T('持仓')}}</text>
          <div class="height20"></div>
          
          <div class="row jbetween">
            <div class="column">
              <text class="font24 text3">{{T('方向')}}</text>

              <div class="height12" v-if="contract_num != -10"></div>
              <div :class="['short-long', Config.upDownBg(10, 'short-long-red', 'short-long-green')]" v-if="contract_num != -10">
                <text :class="['font20',Config.upDownFont(10)]">{{T('做多')}}</text>
              </div>

              <div class="height12" v-if="contract_num != 10"></div>
              <div :class="['short-long', Config.upDownBg(-10, 'short-long-red', 'short-long-green')]" v-if="contract_num != 10">
                <text :class="['font20',Config.upDownFont(-10)]">{{T('做空')}}</text>
              </div>
            </div>
            
            <div class="column ">
              <text class="font24 text3">{{T('持仓量')+'('+T("张")+')'}}</text>
              
              <div class="height12" v-if="contract_num != -10"></div>
              <text class="font24 text2" v-if="contract_num != -10">{{volume0}}</text>
              
              <div class="height12" v-if="contract_num != 10"></div>
              <text class="font24 text2" v-if="contract_num != 10">{{volume1}}</text>
            </div>
        
            
            <div class="column aend">
              <text class="font24 text3">{{T('开仓均价')+'('+tradePairs.investCoin+')'}}</text>
              
              <div class="height12" v-if="contract_num != -10"></div>
              <text class="font24 text2" v-if="contract_num != -10">{{costOpen0}}</text>

              <div class="height12" v-if="contract_num != 10"></div>
              <text class="font24 text2" v-if="contract_num != 10">{{costOpen1}}</text>
            </div>
          </div>
        </div>


        <!-- 当前委托 -->
        <div class="height40"></div>
        <div class="line bg3"></div>
        <div class="height40"></div>
        <div class="column plpr40">
          <text class="font30  text1 ">{{T('当前委托')+'('+(buyList.length+sellList.length)+')'}}</text>
          <WeexBuySellC class="buySell" :buy="buyPrice1" :sell="sellPrice1" :last="detailData.last"></WeexBuySellC>
          <div class="height20"></div>
          <div class="height40"></div>
          <div class="row jbetween">
            <div class="column">
              <text class="font24 text3">{{T('买入')+'('+T("张")+')'}}</text>
              <div class="height20"></div>
              <div class="cloumn astart" v-for="(item, index) in buyList" v-bind:key="index">
                <div class="row acenter">

                  <div :class="['short-long', Config.upDownBg(item.contract_num, 'short-long-red', 'short-long-green')]">
                    <text :class="['font20',Config.upDownFont(item.contract_num)]">{{ item.sellBuyType}}</text>
                  </div>
                    <text class="font24 text2">{{" "+item.amount}}</text>
                </div>
                
                <div class="height12"></div>
                <div class="height20"></div>
              </div>
              
            </div>
            
            <div class="column aend">
              <text class="font24 text3">{{T('价格')+'('+tradePairs.investCoin+')'}}</text>
              <div class="height20"></div>
              <div class="cloumn" v-for="(item, index) in buyList" v-bind:key="index">
                <div class="short-long-null">
                  <text :class="['font24', Config.upDownFont(item.contract_num)]" >{{item.price}}</text>
                <div class="height12"></div>
                </div>
                
                <div class="height20"></div>
              </div>
              
            </div>
            
            <div class="column">
              <text class="font24 text3">{{T('卖出')+'('+T("张")+')'}}</text>
              <div class="height20"></div>
              <div class="column start" v-for="(item, index) in sellList" v-bind:key="index">
                <div class="row acenter">

                  <div :class="['short-long', Config.upDownBg(item.contract_num, 'short-long-red', 'short-long-green')]">
                    <text :class="['font20',Config.upDownFont(item.contract_num)]">{{ item.sellBuyType}}</text>
                  </div>
                  <text class="font24 text2">{{" "+item.amount}}</text>
                </div>
                <div class="height12"></div>
                <div class="height20"></div>
                <!-- <text class="font24 th68 text2">{{item.}}</text> -->
              </div>
            </div>
            
            <div class="column aend">
              <text class="font24 text3">{{T('价格')+'('+ tradePairs.investCoin +')'}}</text>
              <div class="height20"></div>

              <div class="cloumn" v-for="(item, index) in sellList" v-bind:key="index">
                <div class="short-long-null">
                  <text :class="['font24', Config.upDownFont(-1)]" >{{item.price}}</text>
                </div>
                <div class="height12"></div>
                <div class="height20"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="height40"></div>
        <div class="height40"></div>
      </div>
    </scroller>

    <!-- 菜单 -->
    <div class="menu" v-if="showMenu" @click="hideClick">
      <div class="meun-content bg3">
        <text class="font24 text2 meun-text" v-for="(item, index) in menus" v-bind:key="index" @click="menuClick(item)">{{T(item)}}</text>
      </div>
    </div>
  </div>
</template>

<script>
import navigator from "@/_js/navigator";
import modal from "@/_js/modal";
import math from "@/_js/math";
import Config from "@/_js/config";
import amStrategy2 from "@/strategy/amStrategy2";
import broadcast from "@/_js/broadcast";

const weexFunction = weex.requireModule("WeexFunction");
import weexHttp from "@/_js/https"; ;
const WeexMqtt = weex.requireModule("WeexMqtt");


import I18N from "@/_i18n/i18n";
var T = I18N.t;
weexFunction.setTitle(T("执行详情"));
weexFunction.setRightBtn(T('功能'));
export default {
  data() {
    return {
      T: T,
      Config: Config,
      math:math,
      isShow:false,
      contract_num: 10,
      executeId: "", //执行id

      detailData: undefined, //执行信息
      redisMap: undefined, //数据库信息
      configMap: undefined, //执行配置
      followMimic: false, //turn 模拟盘开放跟单
      account: undefined,//用户合约信息
      tradePairs: undefined,//用户api信息
      volume0:undefined,//持仓数量
      costOpen0: undefined,//开仓均价
      volume1:undefined,//持仓数量
      costOpen1: undefined,//开仓均价
      lineChartData: undefined,//折线数据

      positionMap:undefined, //持仓信息
      contractMap:undefined, //合约信息

      
      followMap: undefined, //跟单配置
      
      stopProfit: '', //止盈
      stopLoss: '', //止损
      stopTime: '', //自动终止时间

      buyList: [], //委托买单列表
      sellList: [], //委托卖单列表

      buyPrice1:undefined, //买1价格
      sellPrice1:undefined, //卖1价格
      pairStr:undefined, //交易对字符串

      receiver:undefined,
      showMenu:false, //显示功能
      menus:undefined, //菜单列表

      topic:'', //订阅、发送主题
      topicPair:'', //交易对主题
      msg:'', //发送消息
      timeMqtt:undefined, //MQTT对话保活时间
      newMasgs:'',
    };
  },

  mounted() {

    //执行ID
    this.executeId = navigator.getParam("executeId");

    Config.init(()=>{
      this.initData();
    },[Config.OPT_UP_DOWN]);

    
    //刷新订阅
    broadcast.subscribe('RunInfo', broadcast.EXECUTE_UPDATE, ()=>{
      this.httpExecuteDetail();
    });
  },

  methods: {
    
    initData() {

      this.httpExecuteDetail();

      WeexMqtt.message((data)=>{
          
          if (data.topic == this.topicPair) {
            var messages = JSON.parse(data.message);
            var last = messages[0];
            if (last != undefined && last != '') {
              this.detailData.last = last;
            }
          } else if (data.topic.indexOf(this.topic) >= 0) {
            
            //策略权益  担保资产率  时间  持仓盈亏 持仓盈亏率
            //["100.02977654","8.022663644760187485",1606721058573,"0.1110","0.0000"]
            // var array = data.topic.split('/');
            // var executeId = array[3];
            var message = JSON.parse(data.message);

            var marginBalance = message[0]; //账户权益
            if (marginBalance != undefined && marginBalance != '') {
              this.account.marginBalance = math.xiaoShuDelete0(marginBalance);
            }

            var riskRate = message[1]; //资产担保率
            if (riskRate != undefined && riskRate != '') {
              this.account.riskRate = math.cheng(riskRate,"100", 2, 2);
            }

            if (this.contract_num != 0) {

              var floatEarnings = message[3]; //持仓盈亏
              if (floatEarnings != undefined && floatEarnings != '') {
                this.detailData.floatEarnings = math.xiaoShuDelete0(floatEarnings);
              }

              var floatEarningsRate = message[4]; //持仓盈亏率
              if (floatEarningsRate != undefined && floatEarningsRate != '') {
                this.detailData.floatEarningsRate = math.xiaoShuDelete0(floatEarningsRate);
              }

              this.detailData.realEarnings = math.jia(this.detailData.earnings, this.detailData.floatEarnings); //总收益

              var realEarningsRate = math.chu(this.detailData.realEarnings, this.tradePairs.investCoinnNum); //总收益率
              this.detailData.realEarningsRate = math.cheng(realEarningsRate, '100', 2, 2);
            }
          }
      });
    },

    //处理Mqtt数据
    opMqttData(){

      var pair = this.configMap.tradePairs[0];

      //订阅、发送主题
      this.topic = 'strategy' + '/' + pair.type + '/' +  this.detailData.executeId;

      //发送消息
      var array = [pair.apiId, pair.contractId]
      this.msg  = JSON.stringify(array);

      //交易对主题
      this.topicPair = 'public/market/contract/' + pair.exchangeName.toUpperCase() + '/USDT/' + pair.counterCoin.toUpperCase();
    },

    
    //初始菜单
    initMenu(){

      if (this.detailData.isFollow){
        this.menus = ['消息', '加仓', '减仓', '终止', '成交记录'];
        return;
      } 

      var menus = this.menus = ['消息', '参数', '加仓', '减仓', '终止'];

      if (this.detailData.states == 'SUSPEND') {
        menus.push('重启');
      } else {
        // menus.push('暂停');
      }

      //合约网格，新增网格列表
      if (this.detailData.strategyId == 'WL202007311426363424x') {
        menus.push('网格列表');
      }
      menus.push('成交记录');
      this.menus = menus;
    },

    /*************************************************通信触发*/
    //完全显示
    viewappear() {
      this.initData();
    },

    //完全隐藏
    viewdisappear() {
      if(this.timeMqtt){
        clearTimeout(this.timeMqtt);
      }
      WeexMqtt.message(null);
      WeexMqtt.unSubscribes();
    },

    //右按钮触发
    rightBtn() {
      this.showMenu = !this.showMenu;
    },

    /********************************** HTTP*/
    //http执行详情
    httpExecuteDetail() {
      
      this.detailData = undefined;

      var param = { executeId: this.executeId};
      weexHttp.post("contract/contractDetail",param,true,(data) => {

          if (data.status == 200) {

            this.detailData = data.data;
            this.configMap = this.detailData.config;
            this.tradePairs = this.configMap.tradePairs[0];
            
            this.account = this.detailData.account;
            this.account.riskRate = math.cheng(this.account.riskRate,"100", 2, 2);
            this.positionMap = this.detailData.position;
            this.contractMap = this.detailData.contract;

            //交易数量
            this.detailData.finishOpenCount = this.detailData.finishOpenCount ? this.detailData.finishOpenCount : '0';
            this.detailData.finishCloseCount = this.detailData.finishCloseCount ? this.detailData.finishCloseCount : '0';
            this.detailData.finishBuySellCount = math.jia(this.detailData.finishOpenCount, this.detailData.finishCloseCount);
            //止盈止损
            this.configMap.stopProfit = this.configMap.stopProfit?this.configMap.stopProfit:'';
            this.stopProfit = this.configMap.stopProfit.length > 0 ? (math.cheng(this.configMap.stopProfit, '100') + '%') : '--';
            this.configMap.stopLoss = this.configMap.stopLoss?this.configMap.stopLoss:'';
            this.stopLoss = this.configMap.stopLoss.length > 0 ? (math.cheng(this.configMap.stopLoss, '-100') + '%') : '--';
            this.configMap.stopTime = this.configMap.stopTime?this.configMap.stopTime:'';
            this.stopTime = this.configMap.stopTime.length > 0 ? this.parseTime1(math.getNumber(this.configMap.stopTime)) : '--';
            //交易币、本币、投资币
            this.configMap.inverstCoin = this.configMap.tradePairs[0].investCoin.toUpperCase();
            this.configMap.counterCoin = this.configMap.tradePairs[0].counterCoin.toUpperCase();
            this.configMap.baseCoin = this.configMap.tradePairs[0].baseCoin.toUpperCase();
            
            if(this.tradePairs.investType=="0"){
              this.contract_num = 10;
              this.volume0 = math.xiaoShuDelete0(this.positionMap.buyPosition.volume);//持仓量
              this.costOpen0 = math.xiaoShuDelete0(this.positionMap.buyPosition.costOpen);//开仓均价

            }else if(this.tradePairs.investType=="1"){
              this.contract_num = -10
              this.volume1 = math.xiaoShuDelete0(this.positionMap.sellPosition.volume);//持仓量
              this.costOpen1 = math.xiaoShuDelete0(this.positionMap.sellPosition.costOpen);//开仓均价
            }else if(this.tradePairs.investType=="2"){
              this.contract_num = 0
              this.volume0 = math.xiaoShuDelete0(this.positionMap.buyPosition.volume);//持仓量
              this.costOpen0 = math.xiaoShuDelete0(this.positionMap.buyPosition.costOpen);//开仓均价
              this.volume1 = math.xiaoShuDelete0(this.positionMap.sellPosition.volume);//持仓量
              this.costOpen1 = math.xiaoShuDelete0(this.positionMap.sellPosition.costOpen);//开仓均价
            }

            //收益曲线
            var realEarningsLine = this.detailData.realEarningsLine;
            this.lineChartData = realEarningsLine ? realEarningsLine.items : [];
            
            //交易币、本币 数量/冻结率
            // this.redisMap.baseCoinTotal = math.xiaoshu(this.redisMap.baseCoinTotal, math.getCoin(this.redisMap.baseCoin));
            // this.redisMap.counterCoinTotal = math.xiaoshu(this.redisMap.counterCoinTotal, math.getCoin(this.redisMap.counterCoin));
            // var baseCoinFreezRate = math.chu(this.redisMap.baseCoinFreez, this.redisMap.baseCoinTotal, 4, 2);
            // var counterCoinFreezRate = math.chu(this.redisMap.counterCoinFreez, this.redisMap.counterCoinTotal, 4, 2);
            // this.redisMap.baseCoinFreezRate = math.cheng(baseCoinFreezRate, '100', 2, 2);
            // this.redisMap.counterCoinFreezRate = math.cheng(counterCoinFreezRate, '100', 2, 2);

            //浮动盈亏
            // var xiaoshu = math.getCoin(this.redisMap.inverstCoin);
            // var profitLoss;
            // if (this.redisMap.inverstCoin == this.redisMap.baseCoin) {
            //   var price = math.jian(this.redisMap.curPrice, this.redisMap.costPrice);
            //   profitLoss = math.cheng(price, this.redisMap.counterCoinTotal, xiaoshu, 2);
            // } else {
            //   var cost = math.chu(this.redisMap.baseCoinTotal, this.redisMap.costPrice); //成本价
            //   var cur = math.chu(this.redisMap.baseCoinTotal, this.redisMap.curPrice); //当前价
            //   profitLoss = math.jian(cost, cur, xiaoshu, 2);
            // }
            // this.redisMap.profitLoss = profitLoss;

            //浮动盈亏率
            // var profitLossRate;
            // if (this.redisMap.inverstCoin == this.redisMap.baseCoin) {
            //   var price = math.jian(this.redisMap.curPrice, this.redisMap.costPrice);
            //   profitLossRate = math.chu(price, this.redisMap.costPrice, 4, 2);
            // } else {
            //   var price = math.jian(this.redisMap.costPrice, this.redisMap.curPrice);
            //   profitLossRate = math.chu(price, this.redisMap.costPrice, 4, 2);
            // }
            // profitLossRate = math.cheng(profitLossRate, '100', 2);
            // this.redisMap.profitLossRate = profitLossRate;

            var list = this.detailData.unfinish_orders.orders;
            this.sellList = [];
            this.buyList = [];
            for(let i=0;i<list.length;i++){
              var type = list[i].tradeType;
              if(type=="1"){//买入

                if(list[i].tradeOffset=="1"){
                  list[i].sellBuyType = T("开多");
                  list[i].contract_num = 10;
                  
                }else if(list[i].tradeOffset=="0")
                
                {
                  list[i].sellBuyType = T("平空");
                  list[i].contract_num = 10;
                }
                this.buyList.push(list[i]);
                
              }else if(type=="0"){//卖出
    
                if(list[i].tradeOffset=="1"){
                  list[i].sellBuyType = T("开空");
                  list[i].contract_num = -10;
                }else if(list[i].tradeOffset=="0")
                
                {
                  list[i].sellBuyType = T("平多");
                  list[i].contract_num = -10;
                }

                  this.sellList.push(list[i]);

              }
            }

            //买单从大到小排序
            for (let i = 0; i < this.buyList.length; i++) {
              for (let j = 0; j < this.buyList.length - 1 - i; j++) {
                var price_1 = Number(this.buyList[j].price);
                var price_2 = Number(this.buyList[j+1].price);
                if (price_1 < price_2) {
                  let temp = this.buyList[j+1]; 
                  this.buyList[j+1] = this.buyList[j];
                  this.buyList[j] = temp;
                }
              }
            }

            //卖单从小到大排序
            for (let i = 0; i < this.sellList.length; i++) {
              for (let j = 0; j < this.sellList.length - 1 - i; j++) {
                var price_1 = Number(this.sellList[j].price);
                var price_2 = Number(this.sellList[j+1].price);
                if (price_1 > price_2) {
                  let temp = this.sellList[j+1]; 
                  this.sellList[j+1] = this.sellList[j];
                  this.sellList[j] = temp;
                }
              }
            }
          

            this.buyPrice1 = this.buyList.length ? this.buyList[0].price : undefined;
            
            this.sellPrice1 = this.sellList.length ? this.sellList[0].price : undefined;

            setTimeout(() => { //滑条未绘制，延时刷新
              this.upSlideBar();
            }, 200);
            this.pairStr = JSON.stringify(this.tradePairs);
            //处理Mqtt数据
            this.opMqttData();
            this.mqttSubscribes();
            this.mqttPublishData();
            this.initMenu();
            this.isShow = true;
          } else {
            modal.toast(data.msg);
          }
        }
      );
    },

    /********************************** 订阅*/
    //mqtt订阅主题
    mqttSubscribes() {

      //1、清除旧订阅
      WeexMqtt.unSubscribes(); 

      //2、订阅新主题
      var topic = 'consume' + '/' + this.topic;
      WeexMqtt.subscribes([topic, this.topicPair]);
    },

    //mqtt发送消息
    mqttPublishData() {
      if(this.timeMqtt){
        clearTimeout(this.timeMqtt);
      }

      var topic = 'make' + '/' + this.topic;
      WeexMqtt.publishData(this.msg, topic);
      this.timeMqtt = setTimeout(() => {
        this.mqttPublishData();
      }, 3000);
    },

    /********************************** GET*/
    //获取+字符串
    getAddStr(value) {
      value = math.xiaoShuDelete0(value);
      value = math.addJia(value);
      value = math.xiaoshu(value,2, 2);
      return value;
    },

    //获交易所名称
    getExchangeName() {
      var remark = this.detailData.remark && this.detailData.remark.length ? ('·' + this.detailData.remark) : '';
      return (this.tradePairs.apiName + remark + '（' + this.tradePairs.counterCoin + T('永续')+'/' + this.tradePairs.baseCoin + '）');
    },

    getmul100(value){
      return math.cheng(value,"100",2, 2);
    },

    //根据coin截取长度
    getValueDelete(coin,value) {
      var length;
      if(coin.toUpperCase() =="BTC"){
        length = 6;
      }else if(coin =="%"){
        length = 2;
      }else{
        length = 4;
      }
      
      return math.xiaoshu(value,length, 2);
    },

    //担保资产率，强迫价
    isShowZero(coin,value) {


      if (coin == '%') {
        return math.getNumber(value) == 0 ? '--' : value + '%';
      }

      value = math.xiaoshu(value, math.getCoin(coin), 2);
      return  math.getNumber(value) == 0 ? '--' : value;
    },

    //获得策略状态字符
    getStateStr(detailData) {
      
      var states = detailData.states;
      
      if (states == "EXECUTE") {
        return T("执行中");
      }

      if (states == "SUSPEND") {
        return T("已暂停");
      }

      if (states == "STARTING") {
        return T("启动中");
      }

      if (states == "STOPING") {
        return T("正在终止");
      }
    },

    //时间转换(年月日时分)
    parseTime1(timestamp) {
      var time = new Date(Number(timestamp));

      var year = time.getFullYear();

      var month = time.getMonth() + 1;
      month = month < 10 ? "0" + month : month;

      var day = time.getDate();
      day = day < 10 ? "0" + day : day;

      var hour = time.getHours();
      hour = hour < 10 ? "0" + hour : hour;

      var minute = time.getMinutes();
      minute = minute < 10 ? "0" + minute : minute;

      return year + "/" + month + "/" + day + " " + hour + ":" + minute;
    },

    //获取执行时长
    getExecuteTime(startTime) {
      var time = new Date().getTime();
      var disTime = time - startTime;
      var day = Math.floor(disTime / 86400000);
      var hour = Math.floor((disTime % 86400000) / 3600000);
      var min = Math.floor(((disTime % 86400000) % 3600000) / 60000);
      return day + T("天") + hour + T("时") + min + T("分");
    },

    getMoreOrShort(){
      var investType = this.tradePairs.investType; //0是做多，1 做空, 2 未知
      var type = math.toString(investType);
      if(type=="0"){
        return T('做多')+this.tradePairs.leverRate+'X';
      }

      if(type=="1"){
        return T('做空')+this.tradePairs.leverRate+'X';
      }

      if(type=="2"){
        return T('双向')+this.tradePairs.leverRate+'X';
      }
    },

    getMoreOrShort1(){
      var type = this.tradePairs.investType; //0是做多，1 做空, 2 未知
      if(type=="0"){
        return T('做多');
      }

      if(type=="1"){
        return T('做空');
      }

      if(type=="2"){
        return T('双向');
      }
    },

    /********************************** 更新的方法*/
    //更新滑条
    upSlideBar() {
      var starStr = "0";
      var endStr =
        math.getNumber(this.maxInvest) > math.getNumber(this.moneyNum)
          ? this.moneyNum
          : this.maxInvest;
      endStr = endStr + "";

      var ratio = this.investNum.length
        ? math.chu(this.investNum, endStr, 2, 2)
        : "0";
      ratio = math.getNumber(ratio) > 1 ? "1" : ratio;
      ratio = math.getNumber(endStr) == 0 ? 0 : ratio;

      var a = { starStr: starStr, endStr: endStr, ratio: ratio };

      this.$refs.WeexSlideBar.upSlide(a);
    },

    /********************************** 回调*/

    //总投入资金-输入改变
    onInput(e) {
      this.upSlideBar();
    },

    /********************************** 点击事件 */
    //弹框
    questionClick(click) {
      if(click =="强平价"){
        modal.alert(T("预估担保资产率下降到0%时的价格，实际发生强平的价格以交易所为准。"));
        return;
      }
      if(click =="担保资产率"){
        modal.alert(T("担保资产率越低风险越高，当担保资产率下降至0%时将触发交易所强平，担保资产率 =（账户权益/(持仓担保资产 + 冻结担保资产)）*100%－交易所调整系数。"));
        return;
      }
      if(click =="开仓阈值"){
        modal.alert(T("当担保资产率下降到此值之下时，策略将暂停开仓动作，平仓逻辑不受影响，您可根据风险承受能力自主调节，担保资产率 =（账户权益/(持仓担保资产 + 冻结担保资产)）*100%－交易所调整系数。"));
        return;
      }
      // if(click =="自动转出"){
      //   modal.alert("自动转出");
      //   return;
      // }
    },

    //加仓
    addContractClick(){

      amStrategy2.checkApi(this.tradePairs.apiId, this.tradePairs.apiName, (api)=>{
      
      var limitMap = this.detailData.isFollow ? this.detailData.followInvestLimit : this.detailData.followJson;
      var param = {executeId:this.executeId, 
                  configMap:this.configMap,
                  tradePairs: this.tradePairs,
                  account:this.account,
                  positionMap:this.positionMap,
                  contractMap:this.contractMap,
                  limitMap:limitMap};
        navigator.open('', 'runContract/CAdd',param);
      });
    },

    //隐藏
    hideClick(){
      this.showMenu = false;
    },

    //菜单点击
    menuClick(item){
      this.hideClick();

      if (item == '消息') {

        navigator.open(T('策略消息'), 'strategy/StrategyNotice', {stId:this.executeId});
        return;
      }
      
      if (item == '成交记录') {
        var param = {'executeId':this.executeId,
        'counterCoin':this.tradePairs.counterCoin,
        'baseCoin':this.tradePairs.baseCoin,
        'contract':true};
        navigator.openNative('tradeRecord',param);
        return;
      }

      var states = this.detailData.states;
      if (states == "STARTING" || states == "STOPING" ) {
        modal.toast('请勿频繁操作');
        return;
      }

      if (item == '终止') {
        var parm = {title:T("确认终止"),
                  message:T("策略终止后自动平仓并撤销未成交的委托单。"),
                  okBtn:T("确认"), cancelBtn:T("取消")};
        modal.confirm(parm, (bool)=>{
          if (bool == "true") {
            var apiId = this.tradePairs.apiId;
            var param = {'executeId':this.executeId, 
                        'apiId':apiId,
                        'cancelOrder':true, 
                        'isConvert':true,
                        'isMany':false};

            amStrategy2.httpEnd(param,()=>{
              broadcast.send(broadcast.EXECUTE_UPDATE);
              navigator.back();
            });
          }
        });
        return;
      }

      if (item == '加仓') {
        this.addContractClick();
        return;
      }

      if(item =='减仓'){

        amStrategy2.checkApi(this.tradePairs.apiId, this.tradePairs.apiName, (api)=>{

          var param = {executeId:this.executeId, 
          configMap:this.configMap,
          tradePairs: this.tradePairs,
          account:this.account,
          positionMap:this.positionMap,
          contractMap:this.contractMap};
        
          navigator.open('', 'runContract/CSub',param);
          return;
        });

        
      }
      
      if (item == '参数') {
        
        var param = {'executeId':this.executeId, 
                    'configMap':this.configMap,
                    'signalStates':this.detailData.signalStates,
                    'strategyName':this.detailData.strategyName,
                    'followMap':this.detailData.followJson,
                    'isOpenFollow':this.detailData.isOpenFollow};

        navigator.open('', 'runContract/CParam',param);
        return;
      }

      if (item == '网格列表') {

        var param = {'executeId':this.executeId};
        navigator.open('', 'run/GridListContract',param);
        return;
      }

      if (item == '重启') {

        amStrategy2.showServers(false, true, (server)=>{
          var param = {'executeId':this.executeId};
          if (server) {
            param['serverCode'] = server.serverCode;
          }
          amStrategy2.restart(param, ()=>{
            modal.toast(T('重启成功'));
            broadcast.send(broadcast.EXECUTE_UPDATE);
          });
        });
        return;
      }

      if (item == '暂停') {

        amStrategy2.httpStip(this.executeId, false, ()=>{
          modal.toast(T('暂停成功'));
          broadcast.send(broadcast.EXECUTE_UPDATE);
        });
        return;
      }
    },

  },
};
</script>

 
<style src="@/_css/style.css"></style>
<style scoped>
/* =========================公共样式 */
.all {
  flex: 1;
}
.msg {
  width: 28px;
  height: 28px;
  margin-right: 6px;
}

.ptop5 {
  padding-top: 5px;
}

.th68{
  height: 68px;
  line-height: 68px;
}

.info {
  padding-left: 40px;
  padding-right: 40px;
}
.plpr40 {
  padding-left: 40px;
  padding-right: 40px;
}
.mlmr20 {
  margin-left: 20px;
  margin-right: 20px;
}

.height12 {
  height: 12px;
}

.height28 {
  height: 28px;
}

.height20 {
  height: 20px;
}

.height40 {
  height: 40px;
}

.line1 {
  width: 710px;
  height: 2px;
  margin-top: 40px;
  margin-bottom: 40px;
}
.line {
  margin-left: 40px;
  margin-right: 40px;
  width: 670px;
  height: 2px;
}

.image{
  width: 56px;
  height: 56px;
  border-radius: 28px;
  margin-right: 40px;
}
.bg {
  width: 750px;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.scroller {
  width: 750px;
  z-index: 9;
}
.wrapper {
  padding-top: 40px;
  width: 750px;
  flex-direction: column;
}

/* =========================基本样式 */
.tips-bg {
  background-color: rgba(248, 84, 84, 0.1);
  height: 72px;
  margin-left: 20px;
  margin-right: 20px;
  padding-left: 40px;
  padding-right: 40px;
  border-radius: 8px;
}
.tips-text{
  color: #F85454;
}

.img-right{
  width: 10px;
  height: 16px;
}

.img-question{
  width: 24px;
  height: 24px;
}

.img-earning-rate{
  width: 20px;
  height: 12px;
  border-radius: 2px;
  margin-right: 12px;
}

.short-long-bg{
  border-radius: 4px;
  background-color: rgba(0, 173, 136, 0.1);
  padding-left: 16px;
  padding-right: 16px;
  padding-top: 2px;
  padding-bottom: 2px;
}
.short-long{
  border-radius: 4px;
  padding-left: 16px;
  padding-right: 16px;
  padding-top: 2px;
  padding-bottom: 2px;
}
.short-long-green{
  background-color: rgba(0, 173, 136, 0.1);
}
.short-long-red{
  background-color:  rgba(248, 84, 84, 0.1);
}

.short-long-null{

  padding-top: 2px;
  padding-bottom: 2px;
}

.cell-run {
  flex-direction: row;
  justify-content: space-between;
  padding-left: 40px;
  padding-right: 40px;
}
.cell-run-left{
  flex-direction: column;
}
.cell-run-right {
  flex-direction: column;
  align-items: flex-end;
}
.buySell{
  width: 670px;
  height: 100px;
}

.lineChart{
  margin-top: 40px;
  margin-left: 40px;
  width: 670px;
  height: 450px;
}

/*********************************** 菜单*/
.menu{
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 9;
}
.meun-content {
  position: absolute;
  width: 204px;
  border-radius: 4px;
  
  padding-top: 20px;
  padding-bottom: 20px;

  top: 0;
  right: 0;
}
.meun-text {
  height: 80px;
  line-height: 80px;
  width: 204px;
  text-align: center;
}
</style>